package cn.elegent.txdemo.order.service.impl;

import cn.elegent.ac.ElegentAC;
import cn.elegent.tx.annotation.ElegentTx;
import cn.elegent.tx.context.ElegentACTXContext;
import cn.elegent.txdemo.common.dto.PayDto;
import cn.elegent.txdemo.order.entity.Order;
import cn.elegent.txdemo.order.service.OrderService;
import cn.elegent.txdemo.order.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 *
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private ElegentAC elegentAc;


    @Override
    @ElegentTx(mainName = "pay",childName = "order")
    public void saveOrder(PayDto payDto) {
        Order order=new Order();
        BeanUtils.copyProperties(payDto,order);
        order.setMoney( order.getPrice()*order.getNum() );//金额
        order.setPayTime(LocalDateTime.now()); //购买时间
        order.setStatus(1);
        orderMapper.insert( order);//新增订单

        ElegentACTXContext.setSnapshot("orderId",order.getId());  //把订单号存储为快照
        //elegentAc.publish( "cut_money", payDto );  //通知用户扣款
    }

    @Override
    @Transactional
    public void updateOrderStatus(Long orderId, Integer status) {
        Order order = orderMapper.selectById(orderId);
        order.setStatus(status);
        orderMapper.updateById(order);
    }
}
